package com.yinhai.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.telephony.SmsMessage;

import com.lz.util.Utils;
import com.yinhai.cfg.AppConfig;
import com.yinhai.service.ContactUserServiceImpl;

public class SMS_Receiver extends BroadcastReceiver {
	ContactUserServiceImpl cusi = null;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		cusi = new ContactUserServiceImpl(context);
		if (intent.getAction()
				.equals("android.provider.Telephony.SMS_RECEIVED")) {
			Object[] pdus = (Object[]) intent.getExtras().get("pdus");
			// 不知道为什么明明只有一条消息，传过来的却是数组，也许是为了处理同时同分同秒同毫秒收到多条短信
			// 但这个概率有点小
			SmsMessage[] message = new SmsMessage[pdus.length];
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < pdus.length; i++) {
				// 虽然是循环，其实pdus长度一般都是1
				message[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				sb.append("接收到短信来自:\n");
				sb.append(message[i].getDisplayOriginatingAddress() + "\n");
				sb.append("内容:" + message[i].getDisplayMessageBody());
				if (message[i].getDisplayMessageBody().equals("123")) {
					SharedPreferences preferences = context
							.getSharedPreferences(AppConfig.LOGIN_CONFIG,
									Context.MODE_PRIVATE);
					Editor editor = preferences.edit();
					editor.putString("name", "");
					editor.putString("password", "");
					editor.putString("user_code", "");
					editor.putBoolean("isFirstStart", false);
					editor.putBoolean("isLoginSuccess", false);
					editor.commit();
					cusi.delContact();
					Utils.SaveIsLogin((Activity) context, 0);
				}
				context.sendBroadcast(new Intent("com.im.message"));
				context.sendBroadcast(new Intent("com.im.message.smsdetail"));
				
			}
		}
	}

}
